from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import authenticate, login, logout
from django.urls import reverse_lazy
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import DeleteView

from .forms import MyUserCreationForm,LoginForm,MemberForm,UserDetailForm,GametestForm
from .models import UserProfile,MyGame,Member,gametest
from django.contrib import messages
from django.contrib.auth.models import User
# Create your views here.
def index(request):
    try:
        username = request.session['username']
    except KeyError:
        username = None
    return render(request, "index.html", context={"username": username})

def login_user(request):
    if request.method == 'POST':
        form=LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(request, username=username, password=password)
            if user is not None:
                login(request, user)
                return redirect('/welcome')  # 登录成功后重定向到用户主页面
    else:
        form = LoginForm()
    return render(request, 'login.html', {'form': form})
def welcome(request):
    return render(request, 'welcome.html', {'username': request.user.username})
def logout_user(request):
    logout(request)
    return redirect('/login')

def register_view(request):
    if request.method == 'POST':
        form = MyUserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            return redirect('/success')  # 重定向到成功页面
    else:
        form = MyUserCreationForm()
    return render(request, 'register.html', {'form': form})
def success(request):
    return render(request, 'success.html', {'username': request.user.username})

def redtest(request):
    # return redirect('https://www.baidu.com')
    return redirect('/index')

def functiongroup(request):
    return render(request,'functiongroup.html')

@login_required
def profile_update(request):
    user = request.user
    try:
        profile = user.profile  # 这将引发 RelatedObjectDoesNotExist 如果 profile 不存在
    except UserProfile.DoesNotExist:
        profile = UserProfile.objects.create(user=user)  # 创建新的 Profile 实例
    if request.method == 'POST':
        form = UserDetailForm(request.POST,instance=profile)
        if form.is_valid():
            form.save()
            return redirect('profile') 
    else:
        form = UserDetailForm(instance=profile)
    return render(request, 'update_profile.html', {'form': form})

@login_required
def profile(request):
    user=request.user
    return render(request, 'profile.html',{'user':user})

def member_list(request):
    members = Member.objects.filter(caption=request.user)
    return render(request, 'member_list.html', {'members': members})
def add_member(request):
    user = request.user
    members = Member.objects.filter(caption=request.user)
    try:
        member = user.teamer#这将引发 RelatedObjectDoesNotExist 如果团队关系不存在
    except Member.DoesNotExist:
        member = Member.objects.create()  # 创建新的 Member 实例
    if request.method == 'POST':
        form = MemberForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, 'Member added successfully!')
            return redirect('member_list')  # 假设你有一个名为'member_list'的URL来显示成员列表
    else:
        form = MemberForm()
    return render(request, 'add_member.html', {'form': form,'members':members})


class MemberDeleteView(DeleteView):
    model = Member
    success_url = reverse_lazy('member_list')  # 成功后重定向的URL
    template_name = 'member_confirm_delete.html'  # 自定义删除确认模板

@login_required
def yy(request):
    user=request.user
    return render(request, 'yy.html',{'user':user})
@login_required
def yy_update(request):
    user = request.user
    try:
        gameyy = user.gameyy  # 这将引发 RelatedObjectDoesNotExist 如果 profile 不存在
    except gametest.DoesNotExist:
        gameyy = gametest.objects.create(user=user)  # 创建新的 Profile 实例
    if request.method == 'POST':
        form =GametestForm(request.POST,instance=gameyy)
        if form.is_valid():
            form.save()
            return redirect('yy')
    else:
        form = GametestForm(instance=gameyy)
    return render(request, 'yy_update.html', {'form': form})


# 赛程发布
def joingame(request):
    user = request.user
    try:
        profile = user.profile  # 这将引发 RelatedObjectDoesNotExist 如果 profile 不存在
    except UserProfile.DoesNotExist:
        profile = UserProfile.objects.create(user=user)  # 创建新的 Profile 实例
    if request.method == 'POST':
        form = UserDetailForm(request.POST, instance=profile)
        if form.is_valid():
            form.save()
            return redirect('joingame')
    else:
        form = UserDetailForm(instance=profile)
    return render(request, 'joingame.html', {'form': form})
#比赛预约
def bookgame(request):
    user = request.user
    try:
        gameyy = user.gameyy  # 这将引发 RelatedObjectDoesNotExist 如果 profile 不存在
    except gametest.DoesNotExist:
        gameyy = gametest.objects.create(user=user)  # 创建新的 Profile 实例
    if request.method == 'POST':
        form = GametestForm(request.POST, instance=gameyy)
        if form.is_valid():
            form.save()
    else:
        form = GametestForm(instance=gameyy)
    return render(request, 'bookgame.html', {'form': form})
#比赛签到
def signgame(request):
    return render(request,'signgame.html', {'username': request.user.username})
#弃赛及淘汰确定
@login_required
def losegame(request):
    return redirect('user_delete_confirm')
class UserDeleteConfirmView(DeleteView):
    model = User
    success_url = reverse_lazy('logout')  # 删除后重定向到登出页面或其他适当的页面
    template_name = 'user_delete_confirm.html'

    def get_object(self, queryset=None):
        # 确保只能删除当前登录的用户
        return self.request.user

    def delete(self, request, *args, **kwargs):
        # 在删除之前，你可能想要执行一些清理操作，比如删除关联的数据
        # 这里可以添加那些逻辑
        response = super().delete(request, *args, **kwargs)
        # 执行额外的清理操作（如果有的话）
        return response


#比赛信息发布
def infogame(request):
    return render(request,'infogame.html', {'username': request.user.username})
def news001(request):
    return render(request,'news/001.html')
def news002(request):
    return render(request,'news/002.html')
def news003(request):
    return render(request,'news/003.html')
def news004(request):
    return render(request,'news/004.html')